const express = require("express");
const mySqlite = require("../../sqlite.cjs");
var route = express.Router();

route.get("/getData", async (req, res) => {
  const type = req.query["type"];
  let data = [];
  let sq;
  let meg;
  // console.log("query:?");
  // console.log(req.query);
  try {
    sq = new mySqlite();
    switch (type) {
      case "tableNames":
        //console.log('tables:')
        data = await sq.getTableNames();
        //console.log(data);
        break;
      case "queryTable":
        data = await sq.queryTable({
          tableName: req.query["tableName"],
          select: req.query["select"],
          where: req.query["where"],
          params: req.query["params"],
        });
        break;
      default:
        meg = "\n12 server: url: Invalid type: " + type;
        console.log(meg);
        res.status(400).json({ message: meg });
        return;
    }

    res
      .status(200)
      .json({ data: data, message: "12 server: Data get successfully" });
    //console.log('serverall: data:',{...data})
  } catch (err) {
    //throw new Error('database return error');
    meg = "12 server get: Error processing data:";
    console.error(meg, err);
    console.error(data);
    if (err.message.includes("SQLITE_ERROR: no such table:")) {
      //console.log('rrrrrrrrrrrrrrr')
      res
        .status(401)
        .json({ message: "小提示：无表查询等同于直接取下电脑运行时的内存！ " });
    } else {
      // console.log(err)
      // console.log(Object.keys(err))
      res.status(500).json({ data: data, message: meg, error: err });
    }
  }
});

module.exports = route;
